package com.shengyuan.manage_os.old.ying.erpm;

import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;

import com.shengyuan.manage_os.R;
import com.shengyuan.manage_os.im.common.utils.NetUtils;
import com.shengyuan.manage_os.im.common.utils.ToastUtil;
import com.shengyuan.manage_os.im.ui.SDKCoreHelper;
import com.shengyuan.manage_os.json.JsonUtils;
import com.shengyuan.manage_os.old.ying.boce.jsy.AdminPicForceHandlerTask;
import com.shengyuan.manage_os.old.ying.boce.jsy.PT_yhmc;
import com.shengyuan.manage_os.old.ying.boce.jsy.UpdateManager;
import com.shengyuan.manage_os.old.ying.boce.task.GenericTask;
import com.shengyuan.manage_os.old.ying.boce.task.TaskAdapter;
import com.shengyuan.manage_os.old.ying.boce.task.TaskListener;
import com.shengyuan.manage_os.old.ying.boce.task.TaskParams;
import com.shengyuan.manage_os.old.ying.boce.task.TaskResult;
import com.shengyuan.manage_os.old.ying.erpm.db.Actual_ErpUser;
import com.shengyuan.manage_os.old.ying.erpm.tasks.LoginTask;
import com.shengyuan.manage_os.old.ying.erpm.tasks.SubmitUpdateTask;
import com.shengyuan.manage_os.old.ying.erpm.tasks.Submit_System_Setting_Data_Task;
import com.shengyuan.manage_os.old.ying.erpm.util.SharePreferenceUtil;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;
import com.shengyuan.manage_os.sqlite.SQLiteTools;
import com.shengyuan.manage_os.ui.MainActivity;
import com.shengyuan.manage_os.utils.DeviceUtils;
import com.shengyuan.manage_os.utils.EquipParam;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.platformtools.ECHandlerHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;

import oa.database.bean.Department;

import static com.shengyuan.manage_os.old.ying.erpm.MainApplication.CheckDirectory;

public class LoginActivity extends Activity implements OnClickListener{
	public static PT_yhmc pmUser;
	private EditText login_accounts, login_password;
	private String Tag ="LOGINCODE";
	private Button login_btn;
	private ToggleButton login_btn_state;
	private ProgressDialog	mDialog;
	public static String mSetting;
	public static String[] mSettingArr;
	private SharePreferenceUtil util;
	private boolean isFirstIn = true;
	
	public static final String KEYUSER = "user", KEYPWD ="passwd" , KEYLOGINTYPE = "KEYLOGINTYPE";
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn:
			LoginSystem();
			break;
		default:
			break;
		}
	}
	private Runnable initRunnable = new Runnable() {
		@Override
		public void run() {
				setContentView(R.layout.form_login);
			login_accounts = (EditText)findViewById(R.id.login_accounts);
			login_password = (EditText)findViewById(R.id.login_password);
			login_btn = (Button) findViewById(R.id.login_btn);
			login_accounts.setOnClickListener(LoginActivity.this);
			login_password.setOnClickListener(LoginActivity.this);
			login_btn.setOnClickListener(LoginActivity.this);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_welcome);
		isFirstIn = getIntent().getBooleanExtra("isFirst",true);
		util = SharePreferenceUtil.init(this,"SAVE_USER");
		EquipParam.init(this);
		List<Department> departments = SQLiteTools.queryDepartmentS();

		if(departments.size() == 0){
			JsonUtils.compleJson2(this,R.raw.userdata);
		}

		AdminPicForceHandlerTask task = new AdminPicForceHandlerTask();
//		task.start();



		SDKCoreHelper.getInstance().setLoginSuccess(new SDKCoreHelper.LoginSuccess() {
			@Override
			public void exec(ECDevice.ECConnectState state) {
				if (mDialog!=null) {
					mDialog.dismiss();
				}
				if (state == ECDevice.ECConnectState.CONNECT_SUCCESS){
					Intent intent = new Intent(LoginActivity.this,MainActivity.class);
					startActivity(intent);
					finish();
					System.out.println("$$$$$$$$$$$$$$$$$===LoginActivity==="+SDKCoreHelper.getConnectState()+"*****"+state);
				}else {
					ToastUtil.showMessage("IM登录失败 请重新登录");
				}

			}
		});

	}


	@Override
	protected void onResume() {
		super.onResume();
		if(NetUtils.isOpenNetwork(this)){
			if (isFirstIn){
				if("".equals(util.getId()) && "".equals(util.getName())) {

					ECHandlerHelper.postDelayedRunnOnUI(initRunnable, 3000);
				}else {
					TaskParams params = new TaskParams();
					params.put("username", util.getName());
					params.put("password", util.getPasswd());
					LoginTask loginTask = new LoginTask(this);
					loginTask.setListener(mLoginTaskListener);
					loginTask.execute(params);
				}

			}else {
				setContentView(R.layout.form_login);
				login_accounts = (EditText)findViewById(R.id.login_accounts);
				login_password = (EditText)findViewById(R.id.login_password);
				login_btn = (Button) findViewById(R.id.login_btn);
				login_accounts.setOnClickListener(this);
				login_password.setOnClickListener(this);
				login_btn.setOnClickListener(this);
			}

		}else {
			setContentView(R.layout.activity_no_network);
		}
	}

	@Override
	protected void onStop() {
		MainApplication.mobileHandlerTask.start();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private GenericTask mLoginTask;
	private TaskListener mLoginTaskListener = new TaskAdapter() {
		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {

			if (result == TaskResult.OK) {
				GetProjectDataList();
				GetBaoXiaoDataList();
				GetErpUserList();
//				UpdateSystem();
				if (login_accounts != null) {
					util.setName(login_accounts.getText().toString());
					util.setPasswd(login_password.getText().toString());
					util.setId(SQLiteTools.queryAssignEmployeeByName(login_accounts.getText().toString()).getUid().toString());
					LoginActivity.pmUser.UserName = login_accounts.getText().toString();
				}
				LoginActivity.pmUser.setLogOut(false);

			} else if (result == TaskResult.CANCELLED) {
				Utility.MessageBox(LoginActivity.this,getString(R.string.login_status_invalid_username_or_password));
				if (mDialog!=null) {
					mDialog.dismiss();
				}
			}else{ //离线登录
				Utility.MessageBox(LoginActivity.this,((LoginTask)task).Message);
				System.out.println("@@@@@@@@@@"+((LoginTask)task).Message);
				if (mDialog!=null) {
					mDialog.dismiss();
				}
			}
		}
		


		@Override
		public void onCancelled(GenericTask task) {
			if (mDialog!=null) {
				mDialog.dismiss();
			}
			super.onCancelled(task);
		}


//
		@Override
		public void onPreExecute(GenericTask task) {
			mDialog = Utility.ShowModelDialog(LoginActivity.this, getString(R.string.login_status_logging_in));
			mDialog.show();
		}
	};
	private void LoginSystem() {
		if (!TextUtils.isEmpty(login_accounts.getText()) && !TextUtils.isEmpty(login_password.getText())) {
			mLoginTask = new LoginTask(this);
			mLoginTask.setListener(mLoginTaskListener);
			String user = login_accounts.getText().toString();
			String passwd = login_password.getText().toString();
			MainApplication.pShareUtil.WriteParam(KEYUSER, user);
			MainApplication.pShareUtil.WriteParam(KEYPWD, passwd);
			TaskParams params = new TaskParams();
			params.put("username", user);
			params.put("password", passwd);
			mLoginTask.execute(params);
		} else {
			Utility.MessageBox(LoginActivity.this,getString(R.string.login_status_null_username_or_password));
		}
	}
	
	public void GetProjectDataList() {
		if (LoginActivity.pmUser!=null && LoginActivity.pmUser.UserName!=null) {
			Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
			mSubmitTask.setListener(mTaskListener);
			TaskParams params;
			params = new TaskParams();
			params.put(Submit_System_Setting_Data_Task.TYPENAME,Submit_System_Setting_Data_Task.T_GONGCHENGMINGCHENG_GC);
			params.put(Submit_System_Setting_Data_Task.TYPECODE, LoginActivity.pmUser.UserName);
			mSubmitTask.execute(params);
		}
	}
	public void GetProjectDataList_DaKa() {
		if (LoginActivity.pmUser!=null && LoginActivity.pmUser.UserName!=null) {
			Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
			mSubmitTask.setListener(mTaskListener);
			TaskParams params;
			params = new TaskParams();
			params.put(Submit_System_Setting_Data_Task.TYPENAME, Submit_System_Setting_Data_Task.T_get_data_dakatime);
			params.put(Submit_System_Setting_Data_Task.TYPECODE, LoginActivity.pmUser.UserName);
			mSubmitTask.execute(params);
		}
	}
	
	public void GetBaoXiaoDataList() {
		if (LoginActivity.pmUser.UserName!=null) {
			Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
			mSubmitTask.setListener(mTaskListener);
			TaskParams params;
			params = new TaskParams();
			params.put(Submit_System_Setting_Data_Task.TYPENAME,Submit_System_Setting_Data_Task.T_GONGCHENGMINGCHENG_BAOXIAO);
			params.put(Submit_System_Setting_Data_Task.TYPECODE, LoginActivity.pmUser.UserName);
			mSubmitTask.execute(params);
		}
	}	
	

	
	public void GetErpUserList() {
		if (LoginActivity.pmUser.UserName!=null) {
			Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
			mSubmitTask.setListener(mTaskListener);
			TaskParams params;
			params = new TaskParams();
			params.put(Submit_System_Setting_Data_Task.TYPENAME,Submit_System_Setting_Data_Task.T_ERPUSER);
			params.put(Submit_System_Setting_Data_Task.TYPECODE, LoginActivity.pmUser.UserName);
			mSubmitTask.execute(params);
		}
	}	

	public void GetErpYouPinDanJia() {
		if (LoginActivity.pmUser.UserName!=null) {
			Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
			mSubmitTask.setListener(mTaskListener);
			TaskParams params;
			params = new TaskParams();
			params.put(Submit_System_Setting_Data_Task.TYPENAME,Submit_System_Setting_Data_Task.T_ERPUSER);
			params.put(Submit_System_Setting_Data_Task.TYPECODE, LoginActivity.pmUser.UserName);
			mSubmitTask.execute(params);
		}
	}
	boolean fff = true;
    public TaskListener mTaskListener = new TaskAdapter() {
//    	public ProgressDialog mDialog;
		@Override
		public void onCancelled(GenericTask task) {
			try {
				mDialog.dismiss();
				mDialog = null;
			} catch (Exception e) {
				// TODO: handle exception
			}

		}


		@Override
		public void onPreExecute(GenericTask task) {


		}
    	@Override
    	public void onPostExecute(GenericTask task, TaskResult result) {
    		try {
    			Submit_System_Setting_Data_Task t = (Submit_System_Setting_Data_Task)task;
    			if (result == TaskResult.OK) {
    				if (t.pTypeName.equals(Submit_System_Setting_Data_Task.T_GONGCHENGMINGCHENG_GC) ) {
    					MainApplication.pShareUtil.WriteParam(t.pTypeName, t.pJsonArray.toString());
	    				GetJsonData_ShiShi();
					}
    				if ( t.pTypeName.equals(Submit_System_Setting_Data_Task.T_GONGCHENGMINGCHENG_BAOXIAO)) {
    					MainApplication.pShareUtil.WriteParam(t.pTypeName, t.pJsonArray.toString());
    					GetJsonData_BAOXIAO();
					}
    				if ( t.pTypeName.equals(Submit_System_Setting_Data_Task.T_get_data_dakatime)) {
    					MainApplication.pShareUtil.WriteParam(t.pTypeName, t.pJsonArray.toString());
    					GetJsonData_DaKa();
					}
    				if (t.pTypeName.equals(Submit_System_Setting_Data_Task.T_ERPUSER)) {
    					Actual_ErpUser erpUser1 = new Actual_ErpUser(MainApplication.Instance);
    					if (erpUser1.GetRowsCount()>0) {
    						erpUser1.DeleteData( pmUser.UserName );
    						for (int i = 0; i < t.pJsonArray.length(); i++) {
    							String user = t.pJsonArray.getJSONObject(i).getString(erpUser1.UserName);
    							if (pmUser.UserName.equals(user)) {
        							erpUser1.ID = t.pJsonArray.getJSONObject(i).getLong("ID");
        							erpUser1.UserName = t.pJsonArray.getJSONObject(i).getString(erpUser1.UserName);
        							erpUser1.UserPwd = t.pJsonArray.getJSONObject(i).getString(erpUser1.UserPwd);
        							erpUser1.JiaoSe = t.pJsonArray.getJSONObject(i).getString(erpUser1.JiaoSe);
        							erpUser1.JiaTingDianHua = t.pJsonArray.getJSONObject(i).getString(erpUser1.JiaTingDianHua);
        							erpUser1.IfLogin = t.pJsonArray.getJSONObject(i).getString(erpUser1.IfLogin);
        							erpUser1.Department = t.pJsonArray.getJSONObject(i).getString(erpUser1.Department);
        							erpUser1.Insert_Row();
        							break;
								}
    						}
						}
    					if (erpUser1.GetRowsCount()==0) {
    						for (int i = 0; i < t.pJsonArray.length(); i++) {
    							Actual_ErpUser erpUser = new Actual_ErpUser(MainApplication.Instance);
    							erpUser.ID = t.pJsonArray.getJSONObject(i).getLong("ID");
    							erpUser.UserName = t.pJsonArray.getJSONObject(i).getString(erpUser.UserName);
    							erpUser.UserPwd = t.pJsonArray.getJSONObject(i).getString(erpUser.UserPwd);
    							erpUser.JiaoSe = t.pJsonArray.getJSONObject(i).getString(erpUser.JiaoSe);
    							erpUser.JiaTingDianHua = t.pJsonArray.getJSONObject(i).getString(erpUser.JiaTingDianHua);
    							erpUser.IfLogin = t.pJsonArray.getJSONObject(i).getString(erpUser.IfLogin);
    							erpUser.Department = t.pJsonArray.getJSONObject(i).getString(erpUser.Department);
    							erpUser.Insert_Row();
    							erpUser.close();
							}
    					}
    					erpUser1.close();
//    					finish();
					}
    			}else {
    				Utility.MessageBox(LoginActivity.this,t.mErrorMessage);
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    		}

    	}
    };	
    
    public static void GetJsonData_ShiShi() throws Exception {
		WorkSpaceActivity.ProjectName = new HashMap<String, String>();
		String data = MainApplication.pShareUtil.ReadParam(Submit_System_Setting_Data_Task.T_GONGCHENGMINGCHENG_GC);
		if (data!=null && !data.equals("") && !data.equals("[]") ){
			Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC = new JSONArray(data);
			Submit_System_Setting_Data_Task.A_GONGCHENGMINGCHENG_GC = new String[Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.length()];
			
			for (int i = 0; i < Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.length(); i++) {
				Submit_System_Setting_Data_Task.A_GONGCHENGMINGCHENG_GC[i] = 
						Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("BaoDanLeiXing");
				
				String value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("JieDuanName");
				String key  = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("ProjectName");

				if (!WorkSpaceActivity.ProjectName.containsKey(key)) {
					WorkSpaceActivity.ProjectName.put(key, value);
				}else {
					value = value +"|" + WorkSpaceActivity.ProjectName.get(key);
					WorkSpaceActivity.ProjectName.remove(key);
					WorkSpaceActivity.ProjectName.put(key, value);
				}
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("TaiBanCheLiang");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_WAIZUSHILUN, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("WaiZuJiXie");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_WAIZUJIXIE, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("GongYingShangJia");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_GONYINGSHANG, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("CaiLiaoMingCheng");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_CAILIAOMINGCHENG, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("ZhuangDi");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_ZHUANGDI, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("XieDi");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_XIEDI, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("CheLiangXingHao");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_CHEXING, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("BaoDanLeiXing");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_BiaoDan, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("YuSuanJiaGe");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_YuSuanJiaGe, value);
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("CaiLiaoJiaGe");value = value.replace("\r","");
//				ECApplication.pShareUtil.WriteParam(Submit_System_Setting_Data_Task.T_CaiLiaoJiaGe, value);

				//实施结束时间
//				value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_GC.getJSONObject(i).getString("ShiShiTimeE");value = value.replace("\r","");
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				WorkSpaceActivity.ShiShiTimeE = formatter.parse(value);
				
			}   
		}
//		Utility.MessageBox(ECApplication.Instance.getString(R.string.setting_success_system_data_project));
	}



    public static void GetJsonData_BAOXIAO() throws Exception {
		WorkSpaceActivity.ProjectName_BaoXiao = new HashMap<String, String>();
		String data = MainApplication.pShareUtil.ReadParam(Submit_System_Setting_Data_Task.T_GONGCHENGMINGCHENG_BAOXIAO);
		if (data!=null && !data.equals("") && !data.equals("[]") ){
			Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_BAOXIAO = new JSONArray(data);
			Submit_System_Setting_Data_Task.A_GONGCHENGMINGCHENG_BAOXIAO = new String[Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_BAOXIAO.length()];
			
			for (int i = 0; i < Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_BAOXIAO.length(); i++) {
				String value = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_BAOXIAO.getJSONObject(i).getString("JieDuanName");
				String key  = Submit_System_Setting_Data_Task.J_GONGCHENGMINGCHENG_BAOXIAO.getJSONObject(i).getString("ProjectName"); 
					if (!WorkSpaceActivity.ProjectName_BaoXiao.containsKey(key)) {
						WorkSpaceActivity.ProjectName_BaoXiao.put(key, value); 
					}else {
					value = value +"|" + WorkSpaceActivity.ProjectName_BaoXiao.get(key);
					WorkSpaceActivity.ProjectName_BaoXiao.remove(key);
					WorkSpaceActivity.ProjectName_BaoXiao.put(key, value);
				}
			}   
		}
//		Utility.MessageBox(ECApplication.Instance.getString(R.string.setting_success_system_data_baoxiao));
	}
    
    public static void GetJsonData_DaKa() throws Exception {
		//WorkSpaceActivity.ProjectName_BaoXiao = new HashMap<String, String>();
		String data = MainApplication.pShareUtil.ReadParam(Submit_System_Setting_Data_Task.T_get_data_dakatime);
		if (data!=null && !data.equals("") && !data.equals("[]") ){
			JSONArray jsonArray = new JSONArray(data);
			mSetting = jsonArray.getJSONObject(0).getString("Setting");	
			MainApplication.pShareUtil.WriteParam("DAKAI", mSetting);
			//Utility.MessageBox(mSetting);
		}else {
			mSetting = MainApplication.pShareUtil.ReadParam("DAKAI");
		}
		if (mSetting!=null) {
			mSettingArr = mSetting.split("\r\n");
		}
		
	}

}

